package cm.studapp.database;

import cm.studapp.helpers.TimeHelper;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.widget.TextView;

public class DbManager {
	DbOpenHelper dbHelper;
    SQLiteDatabase db;
    DbQuerys querys;
    TimeHelper th;
	public DbManager(Context ctx) {
		// TODO Auto-generated constructor stub
		dbHelper=new DbOpenHelper(ctx, "StudAppdb",null,1);
		querys=new DbQuerys();
		th = new TimeHelper();
	}
	

	public DbManager(Service serviceHandler) {
		// TODO Auto-generated constructor stub
		dbHelper = new DbOpenHelper(serviceHandler, "StudAppdb",null,1);
		querys=new DbQuerys();
		th = new TimeHelper();
	}
	
	public void setCheckedDuty(int dutyId){
		db = dbHelper.getWritableDatabase();
		
		
		ContentValues values = new ContentValues();
		values.put("consultada", 1);
		String[] whereArgs = {""+dutyId};
		db.update("deber", values, "id=?", whereArgs );
		
		db.close();
		
	
	}


	public boolean insertSemester(long initDate, long endDate){
		db = dbHelper.getWritableDatabase();
		ContentValues newSemester = new ContentValues();
		newSemester.put("fecha_inicio", initDate);
		newSemester.put("fecha_termino", endDate);
		if(db.insert("semestre", null, newSemester)>0){
			db.close();
			return true;
		}
		else{
			db.close();
			return false;
		}		
	}
	
	
	
	public boolean isSemesterSetted(){
		db = dbHelper.getReadableDatabase();
		
		Cursor cs = db.rawQuery("SELECT * FROM semestre", null);
		boolean res = (cs.getCount()!=0);
		db.close();
		cs.close();
		
		return res;
	}
	
	public long insertRepActivity(String name, String type,String mode, String place ,String obs){
		db=dbHelper.getWritableDatabase();
		ContentValues newRepAct = new ContentValues();
		newRepAct.put("nombre", name);
		newRepAct.put("tipo", type);
		newRepAct.put("modo", mode);
		newRepAct.put("lugar", place);
		newRepAct.put("observacion", obs);
		long res;
		if((res=db.insert("act_repetida", null, newRepAct))>0){
			db.close();
			return res;
		}
		else{
			db.close();
			return res;
		}
	}
	
	public boolean insertControl(String name, long ramo_id, long initHour, long endHour,long mode,String obs){
		db=dbHelper.getWritableDatabase();
		ContentValues newControl = new ContentValues();
		newControl.put("nombre", name);
		newControl.put("ramo_id", ramo_id);
		newControl.put("hora_inicio", initHour);
		newControl.put("hora_termino", endHour);
		newControl.put("modo", mode);
		newControl.put("observacion", obs);
		if(db.insert("act_repetida", null, newControl)>0){
			db.close();
			return true;
		}
		else{
			db.close();
			return false;
		}
	}

	public boolean insertDuty(String name, int ramo_id, long initHour, int mode,long endHour,String obs){
		db=dbHelper.getWritableDatabase();
		ContentValues newHomework = new ContentValues();
		newHomework.put("ramo_id", ramo_id);
		newHomework.put("tipo", mode);
		newHomework.put("nombre", name);
		newHomework.put("hora_inicio", initHour);
		newHomework.put("hora_termino", endHour);
		newHomework.put("observacion", obs);
		newHomework.put("modo", 0);
		if(db.insert("deber", null, newHomework)>0){
			db.close();
			return true;
		}
		else{
			db.close();
			return false;
		}
	}
	
	
	public boolean insertModule(long act_id, long initHour, long endHour){
		db=dbHelper.getWritableDatabase();
		ContentValues newModule = new ContentValues();
		newModule.put("actividad_id", act_id);
		newModule.put("hora_inicio", initHour);
		newModule.put("hora_termino", endHour);
		if(db.insert("modulo", null, newModule)>0){
			db.close();
			return true;
		}
		else{
			db.close();
			return false;
		}
	}
	
	
	public Cursor getAllEvents(){
		db=dbHelper.getReadableDatabase();
		Cursor cursor= db.rawQuery(querys.getQuery("getAllEvents"), null);
		return cursor;
	}
	
	public Cursor getTodayEvents(long today){
		db=dbHelper.getReadableDatabase();
		long endDay=today+(24*60*60*1000);
		String [] args =new String[]{""+today,""+endDay};
		return db.rawQuery(querys.getQuery("getTodayAgenda"), args); 
		
	}
	
	public Cursor getFinishedHomeworks(){
		db=dbHelper.getReadableDatabase();
		
		String [] args =new String[]{""+th.getActualTimeInMillis(),""+0};
		Cursor cs = db.rawQuery("SELECT * FROM deber WHERE hora_termino < ? AND consultada = ?", args); 
		return cs;
	}
	public void popActSemModules(long actId, long initHour, long endHour){
		/*Pobla la base de datos con todos los datos de modulos de una actividad repetida*/
		
		//1) Obtener la fecha de inicio y de termino del semestre:
		
		db = dbHelper.getReadableDatabase();
		Cursor sem = db.rawQuery("SELECT * FROM semestre", null);
		sem.moveToFirst();
		long endSem = sem.getLong(2);
		long semana = (1000*60*60*24*7); //milisegundos que tiene una semana xD
		long duracion = endHour-initHour; //Del modulo 
		sem.close();
		db.close();
		

		
		//iniciar el poblado hasta el final del semestre:
		for(long i=initHour; i<= endSem; i=i+semana){
			insertModule(actId, i,i+duracion );
		}
		
	}
	
	public Cursor getAllStatistics(){
		db = dbHelper.getReadableDatabase();
		return db.rawQuery("SELECT * from estadistica", null);
	}
	
	public Cursor getTotalStats(){
		db = dbHelper.getReadableDatabase();
		return db.rawQuery("SELECT SUM(cumplidos), SUM(no_cumplidos) FROM estadistica", null);
	}
	
	public Cursor getPartialStats(int type){
		db = dbHelper.getReadableDatabase();
		String [] args = new String[]{""+type};
		return db.rawQuery(querys.getQuery("getPartialStat"), args);
	}

	public Cursor getRepActData(int id){
		db = dbHelper.getReadableDatabase();
		String args[] = {""+id};
		return db.rawQuery("SELECT * FROM act_repetida WHERE id=?", args);
		
	}
	
	public Cursor getWeekModules(int id){
		db = dbHelper.getReadableDatabase();
		long today = th.getTodayInMillis();
		long todayNextWeek = today + (7*24*60*60*1000);
		String args[] = {""+id,""+th.getTodayInMillis(),""+todayNextWeek};
		return db.rawQuery(querys.getQuery("getWeekModules"), args);
	}


	public Cursor getHomeWorks(int idAct, int type) {
		// TODO Auto-generated method stub
		db = dbHelper.getReadableDatabase();
		long today = th.getTodayInMillis();
		String args[] = {""+idAct,""+today,""+type};
		
		return db.rawQuery(querys.getQuery("getHomeworks"), args);
	}


	public String getActName(int idAct) {
		db = dbHelper.getReadableDatabase();
		String[] args = {""+idAct};
		Cursor aux=db.rawQuery("SELECT nombre FROM act_repetida WHERE id=?", args);
		aux.moveToFirst();
		String res = aux.getString(0);
		// TODO Auto-generated method stub
		aux.close();
		db.close();
		return res;
	}


	public Cursor getAllActRep() {
		// TODO Auto-generated method stub
		db =dbHelper.getReadableDatabase();
		Cursor aux=db.rawQuery("SELECT * FROM act_repetida", null);
		return aux;
	}

	public Cursor getDuty(int dutyId){
		db = dbHelper.getReadableDatabase();
		String[] args = {""+dutyId};
		
		return db.rawQuery("SELECT * FROM deber WHERE id = ?" , args);
		
	}
	
	public void insertStatistics(int idDuty, int resp) {
		// TODO Auto-generated method stub
		Cursor hw = getDuty(idDuty);
	
		hw.moveToFirst();

		long end = hw.getLong(5);
		for(long index=hw.getLong(4);index<=end;index=index+(30*60*1000)){
		String initHour = th.millisToHour(index);
		
		int hourModifier = Integer.parseInt(initHour.substring(0, 2));
		int restInit = Integer.parseInt(initHour.substring(3));
		

		
		int daysModifier = th.weekNumberDay(index)+1;
		
		int bloque = (16*hourModifier)+daysModifier;
		
		if(restInit >=30)
			bloque=bloque+8;
		
		
		
		
		db=dbHelper.getWritableDatabase();
		
		//Agregar la estadistica a todos los bloques que toca:
		
/*
		Cursor statInfo = getStatBloqData(bloque);
		boolean isCreated = (statInfo.getCount() != 0);
	*/
		ContentValues content = new ContentValues();
		content.put("tipo", hw.getInt(2));
		content.put("hora_termino", end);
		if(resp==1)
			content.put("cumplidos", 1);
		else
			content.put("no_cumplidos", 1);
		content.put("bloque", bloque);
		db.insert("estadistica", null, content);
		db.close();		
		}
		
		
		hw.close();
	}


	public Cursor getStatBloqsData() {
		// TODO Auto-generated method stub
		db = dbHelper.getReadableDatabase();
		
		String[] columns = {"bloque", "SUM(cumplidos)","SUM(no_cumplidos)"};
		String groupBy = "bloque";
		Cursor cs = db.query("estadistica", columns , null, null, groupBy , null, null);
		

		return cs;
	}


	public long getInitSemester() {
		db = dbHelper.getReadableDatabase();
		
		Cursor cs = db.rawQuery("SELECT * FROM semestre", null);
		if(cs.moveToFirst()){
			long res = cs.getLong(1);
			cs.close();
			db.close();
			return res;
		}
		else
			return -1;
	}


	public Cursor getStats(int typeMod, long timeMod) {
		db = dbHelper.getReadableDatabase();
		if(typeMod!=-1){
			String [] args = new String[]{""+typeMod, ""+timeMod};
			return db.rawQuery(querys.getQuery("getStats"), args);
		}
		else{
			String [] args = new String[]{""+timeMod};
			return db.rawQuery(querys.getQuery("getStats2"), args);			
		}
	}


	public Cursor getTodayDutys(long today) {
		db=dbHelper.getReadableDatabase();
		long endDay=today+(24*60*60*1000);
		String [] args =new String[]{""+today,""+endDay};
		return db.rawQuery(querys.getQuery("getTodayDutys"), args); 
	
	}
}
